<template>
  <div class="app-container">
    <div id="container" v-loading="loading"></div>
    
    <div class="control-panel">
      <el-button 
        type="primary" 
        @click="initRoute" 
        :disabled="isTracking || loading"
        v-hasPermi="['product:product:list']"
      >
        规划路线
      </el-button>
      <el-button 
        type="primary" 
        @click="startTracking" 
        :disabled="isTracking || loading"
       v-hasPermi="['product:product:list']"
      >
        快递实时位置
      </el-button>
      <el-button 
        type="primary" 
        @click="moveDelivery" 
        :disabled="isTracking || loading"
        v-hasPermi="['product:product:list']"
      >
        模拟配送
      </el-button>
    </div>

    <!-- 新增的输入框区域 -->
    <div class="app-container">
      <el-form :inline="true" :model="inputForm" class="input-form">
        <el-form-item label="物流单号">
          <el-input 
            v-model="inputForm.logisticsId" 
            placeholder="请输入物流单号"
            clearable
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { getLogisticsaddress,listLogisticsaddress } from "@/api/logisticsaddress/logisticsaddress";
import { sendMessage } from "@/api/webhook/webhook";
import { getCurrentInstance } from 'vue';
import { updateLogisticsmaster } from "@/api/logisticsmaster/logisticsmaster";

const { proxy } = getCurrentInstance();

// 响应式状态
const map = ref(null);
const pathSimplifier = ref(null);
const navg = ref(null);
const deliveryMarker = ref(null);
const isTracking = ref(false);
const trackingInterval = ref(null);
const routePath = ref([]);
const people = ref([]);
const currentPositionIndex = ref(0);
const loading = ref(false);
const mockRoute = ref([]);
const inputForm = ref({
  logisticsId: ''
});
const geocoder = ref(null);
const driving = ref(null); // 驾车路线规划实例

// 初始化地图
const initMap = () => {
  loading.value = true;
  map.value = new AMap.Map('container', {
    zoom: 13,
    center: [106.623, 26.423],
    viewMode: '2D'
  });

  // 初始化地理编码工具
  geocoder.value = new AMap.Geocoder({
    city: "全国",
  });

  // 初始化驾车路线规划
  driving.value = new AMap.Driving({
    map: map.value,
    policy: AMap.DrivingPolicy.LEAST_TIME, // 最短时间
    hideMarkers: true // 隐藏默认标记
  });

  AMapUI.load(['ui/misc/PathSimplifier'], (PathSimplifier) => {
    if (!PathSimplifier.supportCanvas) {
      proxy.$modal.msgError('当前环境不支持Canvas');
      return;
    }

    pathSimplifier.value = new PathSimplifier({
      zIndex: 100,
      map: map.value,
      getPath: (pathData) => pathData.path,
      renderOptions: {
        pathLineStyle: {
          strokeStyle: '#3366FF',
          lineWidth: 6,
          dirArrowStyle: {
            step: 72,
            strokeStyle: '#3366FF',
            fillStyle: '#3366FF',
            scale: 0.8
          }
        }
      }
    });
    loading.value = false;
  });
};

// 地址转经纬度
const addressToLngLat = (address) => {
  return new Promise((resolve, reject) => {
    geocoder.value.getLocation(address, (status, result) => {
      if (status === "complete" && result.info === "OK") {
        resolve(result.geocodes[0].location);
      } else {
        reject(new Error(`地理编码失败: ${result.info}`));
      }
    });
  });
};

// 初始化路线 - 使用高德地图API路径规划
const initRoute = async () => {
  try {
    const query = {
      logisticsId: inputForm.value.logisticsId
    };
    const response = await listLogisticsaddress(query);
    const row = response.rows[0];
    
    // 获取起点和终点坐标
    const start = await addressToLngLat(row.currentLocation);
    const end = await addressToLngLat(
      `${row.province}${row.city}${row.district}${row.street}${row.detailAddress}`
    );

    // 使用高德地图驾车路线规划
    driving.value.search(
      new AMap.LngLat(start.lng, start.lat),
      new AMap.LngLat(end.lng, end.lat),
      (status, result) => {
        if (status === 'complete') {
          if (result.routes && result.routes.length > 0) {
            // 获取规划路线路径
            const path = result.routes[0].steps.reduce((acc, step) => {
              return acc.concat(step.path);
            }, []);
            
            routePath.value = path;
            mockRoute.value = path;
            
            // 显示路线
            pathSimplifier.value.setData([{
              name: '配送路径',
              path: routePath.value
            }]);

            navg.value = pathSimplifier.value.createPathNavigator(0, {
              loop: false,
              speed: 1000
            });

            // 添加起点和终点标记
            addMarker(routePath.value[0], '起点', 'https://webapi.amap.com/theme/v1.3/markers/n/start.png');
            addMarker(routePath.value[routePath.value.length - 1], '终点', 'https://webapi.amap.com/theme/v1.3/markers/n/end.png');
            
            // 调整地图视野
            map.value.setFitView();
          } else {
            proxy.$modal.msgError('未找到可行路线');
          }
        } else {
          proxy.$modal.msgError('路线规划失败');
        }
      }
    );
  } catch (error) {
    console.error(error);
    proxy.$modal.msgError('路线加载失败: ' + error.message);
  }
};

// 修改后的添加标记方法
const addMarker = (position, title, iconUrl, size = 36) => {
  return new AMap.Marker({
    position: position,
    title: title,
    map: map.value,
    icon: new AMap.Icon({
      image: iconUrl,
      size: new AMap.Size(size, size),
      imageSize: new AMap.Size(size, size),
      imageOffset: new AMap.Pixel(0, 0)
    }),
    offset: new AMap.Pixel(-size/2, -size/2) // 居中显示
  });
};

// 修改后的startTracking方法
const startTracking = () => {
  if (isTracking.value) return;
  currentPositionIndex.value = 0;
  
  if (deliveryMarker.value) {
    map.value.remove(deliveryMarker.value);
  }

  const query = {
    logisticsId: inputForm.value.logisticsId
  };
  listLogisticsaddress(query).then(async (response) => {
    const row = response.rows[0];
    const start = await addressToLngLat(row.currentLocation);
    
    deliveryMarker.value = addMarker(
      [start.lng, start.lat],
      '配送员位置', 
      'https://tse3-mm.cn.bing.net/th/id/OIP-C.pWqbAfzqeYJhcl69nktSNgHaHa?rs=1&pid=ImgDetMain&cb=idpwebp2&o=7&rm=3',
      40 // 设置大小为40x40像素
    );
  });
};

const moveDelivery = () => {
  currentPositionIndex.value++;
  
  if (currentPositionIndex.value >= routePath.value.length) {
    stopTracking();
    proxy.$modal.msgSuccess('配送已完成');

    const message = '配送已完成';
    const data = {logisticsId: inputForm.value.logisticsId, status: "COMPLETED"};
    updateLogisticsmaster(data).then(response => {});
    sendMessage(message);
    return;
  }
  
  const newPosition = routePath.value[currentPositionIndex.value];
  deliveryMarker.value.setPosition(newPosition);
  navg.value.moveToPoint(currentPositionIndex.value, 0);
  map.value.setCenter(newPosition);
};

const stopTracking = () => {
  isTracking.value = false;
  if (trackingInterval.value) {
    clearInterval(trackingInterval.value);
    trackingInterval.value = null;
  }
};

const loadAMap = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap && window.AMap.Driving) {
      resolve();
      return;
    }

    window._AMapSecurityConfig = {
      securityJsCode: "51d0743c098be80dffaf438143ab67b9"
    };

    const script = document.createElement('script');
    script.src = 'https://webapi.amap.com/maps?v=2.0&key=a1d0ab963e056999210ecd8c120fa60f&plugin=AMap.Driving,AMap.Geocoder';
    script.onload = () => {
      // 加载UI库
      const uiScript = document.createElement('script');
      uiScript.src = 'https://webapi.amap.com/ui/1.1/main.js';
      uiScript.onload = resolve;
      uiScript.onerror = reject;
      document.head.appendChild(uiScript);
    };
    script.onerror = reject;
    document.head.appendChild(script);
  });
};

onMounted(() => {
  loadAMap()
    .then(initMap)
    .catch(err => {
      console.error('地图加载失败:', err);
      proxy.$modal.msgError('地图加载失败，请刷新重试');
    });
});

onBeforeUnmount(() => {
  stopTracking();
  if (map.value) {
    map.value.destroy();
  }
});
</script>

<style scoped>
.app-container {
  width: 100%;
  height: 100%;
  position: relative;
}

#container {
  width: 100%;
  height: 600px;
}

.control-panel {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 999;
  background: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 4px;
  display: flex;
  gap: 10px;
}

.input-form {
  padding: 10px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  margin: 10px;
}
</style>